<?php

/**
 * Clase base para las acciones del backend
 **/

abstract class sgeActions extends sfActions
{

	public function getCredential()
	{
		if (!$this->getRequest()->isXmlHttpRequest())
		{
			$routeOptions = $this->getRoute()->getOptions();
			$routeParams = $this->getRoute()->getParameters();

			if ('historic' === $routeParams['action'] || 'compare' === $routeParams['action'])
			{
				return sfConfig::get('audit_credential');
			}
			else
			{
				if (isset($routeOptions['model']))
					return $routeOptions['model'];
			}
		}
		return null;
	}

	protected function getFilterInfo()
	{
		$display = array_flip($this->configuration->getFilterDisplay());
		$filters = array();
		if (count($display) > 0)
			$filters = array_intersect_key($this->getFilters(), array_flip($this->configuration->getFilterDisplay()));
		else
			$filters = $this->getFilters();

		if (!$filters)
			return null;

		$this->getContext()->getConfiguration()->loadHelpers('SEstadisticas');

		$info = array();
		$default = $this->configuration->getFieldsDefault();

		foreach ($filters as $name => $filter)
		{
			$field = $default[$name];

			$label = isset($field['label']) ? $field['label'] : sfInflector::humanize($name);

			if ($field['type'] === 'ForeignKey')
			{
				$info[] = array('label' => $label, 'value' => Doctrine_Core::getTable($field['foreign_class'])->find($filter));
			}
			else if (is_array($filter))
			{
				if (isset($field['renderer']))
				{
					$info[] = array('label' => $label, 'value' => call_user_func($field['renderer'], $filter['text']));
				}
				else
				{
					$info[] = array('label' => $label, 'value' => implode(' - ', $filter));
				}
			}
			else
			{
				if (isset($field['renderer']))
				{
					$info[] = array('label' => $label, 'value' => call_user_func($field['renderer'], $filter));
				}
				else
				{
					$info[] = array('label' => $label, 'value' => $filter);
				}
			}
		}

		return $info;
	}

	public function executeListReport(sfWebRequest $request)
	{
		$this->getResponse()->clearHttpHeaders();
		$this->getResponse()->setContent('');

		$data = $this->buildQuery()->execute();
		$filters = $this->getFilterInfo();
		$context = sfContext::getInstance();

		$view = new sgeReportView($context, $context->getActionStack()->getLastEntry()->getModuleName(), '_list_report', '');
		$view->setPartialVars(array('data' => $data, 'filters' => $filters));

		$pdf = new sgePDF();
		$pdf->setup($this->configuration->getReportTitle(), $this->configuration->getReportFilename());
		$pdf->writeReportTitle();

		if ($filters)
			$pdf->writeFilters($filters);

		//listado
		$pdf->writeHTML($view->render());

		$pdf->createDocument();

		throw new sfStopException();
	}

	protected function logError($message)
	{
		$this->dispatcher->notify(new sfEvent($this, 'application.log', array('priority' => sfLogger::ERR, $message)));
	}

}
